# -*- coding: utf-8 -*-
#  @author  Bink
#  @date  2020/10/11 16:31
# @Email : 2641032316@qq.com

# todo
#  统计dorm.txt文件中，学生的晚归次数。
#  学生id，具体时间，进出方向(0进寝室，1出寝室)

import re
import time

import pandas as pd

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('max_colwidth', None)

file_dorm = pd.read_table("../resources/train/dorm_train.txt",
                          dtype=str,
                          delimiter=','
                          )
df_dorm = pd.DataFrame(file_dorm)
df_dorm.columns = ['id', 'actualTime', 'direction(0:in 1:out)']
df_dorm['id'].astype(int)

df_dorm['date'] = [re.match(r'(\d{4}/\d{1,2}/\d{1,2})', dateStr).group() for dateStr in df_dorm['actualTime']]
df_dorm['month'] = [re.match(r'(\d{4}/\d{1,2})', dateStr).group() for dateStr in df_dorm['actualTime']]
df_dorm['year'] = [re.match(r'(\d{4})', dateStr).group() for dateStr in df_dorm['actualTime']]

# df_dorm['actualTime'] = (df_dorm['actualTime'].apply(lambda x:
#                                                      int(time.mktime(time.strptime(x, "%Y/%m/%d %H:%M:%S")))
#                                                      )
#                          *
#                          df_dorm['direction(0:in 1:out)'].apply(lambda x:
#                                                                 -1 if int(x) == 0
#                                                                 else
#                                                                 1
#                                                                 )
#                          )

df_dorm['isLate'] = df_dorm['actualTime'].apply(lambda x:  # "2014/01/21 04:53:55"
                                                int(time.mktime(time.strptime(x, "%Y/%m/%d %H:%M:%S"))) not in
                                                range(
                                                    int(time.mktime(
                                                        time.strptime(x.replace(x[-8:], '06:30:00'),
                                                                      "%Y/%m/%d %H:%M:%S")))
                                                    ,
                                                    int(time.mktime(
                                                        time.strptime(x.replace(x[-8:], '23:30:00'),
                                                                      "%Y/%m/%d %H:%M:%S")))
                                                )
                                                )

df = df_dorm[df_dorm['isLate'] == True].set_index(['id', 'year', 'month', 'date'])[:].sort_index()
# df.to_csv("./output/dormLate.csv")

# print(df.loc[:, ['isLate']].groupby(['id']).count())
# print(df.loc[:, ['isLate']].groupby(['id', 'year']).count())
print(df.loc[:, ['isLate']].groupby(['id', 'year', 'month']).count())
